package com.xiaochi.subject.application.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * fegin拦截器
 *
 * 一般fegin拦截器都在调用方写
 * fegin一般都是三次重试机制
 * 这样loginId才能在另一个拦截器上找到
 *
 * todo fegin拦截器
 * auth服务 ——> fegin拦截器 ——> subject服务
 * 所以是先到这个fegin拦截器 再到LoginInterceptor拦截器 并且把loginId传过去 没有这个拦截器 LoginInterceptor拦截器拿不到loginId
 *
 * @author zqx
 * @since 2024/9/5
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        if (Objects.nonNull(request)){
            String loginId = request.getHeader("loginId");
            if (StringUtils.isNotBlank(loginId)){
                requestTemplate.header("loginId",loginId);
            }
        }
    }
}
